/* 
 * Cashbox is the legal property of its developers, whose names are listed in the copyright file included
 * with this source distribution.
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#import "CBPluginController.h"
#import <Cashbox/CBPlugin.h>

@interface CBPluginController (PRIVATE)
- (void)loadPluginsInDirectory:(NSString *)path;
@end

@implementation CBPluginController

- (id)init {
	if ((self = [super init])) {
		plugins = [[NSMutableArray alloc] init];
	}
	return self;
}

- (void)dealloc {
	[plugins release];
	[super dealloc];
}

- (void)controllerDidLoad {
	// bundle for class works with the unit tests, but getting the main bundle does not
	[self loadPluginsInDirectory:[[NSBundle bundleForClass:[CBCashbox class]] builtInPlugInsPath]];

	NSString *searchPath;
	NSArray *librarySearchPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSAllDomainsMask - NSSystemDomainMask, YES);
	NSEnumerator *searchPathEnumerator = [librarySearchPaths objectEnumerator];
	while(searchPath = [searchPathEnumerator nextObject]) {
		[self loadPluginsInDirectory:[searchPath stringByAppendingPathComponent:@"Application Support/Cashbox/PlugIns"]];
    }
	
}

- (void)controllerWillClose {
	CBPlugin *plugin;
	NSEnumerator *pluginEnumerator = [plugins objectEnumerator];
	while ((plugin = [pluginEnumerator nextObject])) {
		[plugin pluginWillClose];
	}
	[plugins removeAllObjects];
}

- (void)loadPluginsInDirectory:(NSString *)path {
	NSString *bundlePath;
	NSEnumerator *bundleEnumerator = [[[NSFileManager defaultManager] directoryContentsAtPath:path] objectEnumerator];
	if (bundleEnumerator) {
		while(bundlePath = [bundleEnumerator nextObject]) {
			if ([[bundlePath pathExtension] isEqualToString:@"cashboxPlugin"]) {
				NSBundle *bundle = [NSBundle bundleWithPath:[path stringByAppendingPathComponent:bundlePath]];
				Class principal = [bundle principalClass];
				CBPlugin *plugin = [[[principal alloc] init] autorelease];
				[plugins addObject:plugin];
				[plugin pluginDidLoad];
			}
		}
	}
}

- (NSArray *)plugins {
	return plugins;
}

@end
